<?php
/**
 * 
 * TransactionHistoryAPIClient
 * 
 * A class which facilitates the interaction with AlertPay's 
 * TransactionHistory API. TransactionHistoryAPIClient class allows user (merchant) to create 
 * the data to be sent to the API in the correct format and 
 * retrieve the response. 
 * 
 * 
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY
 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
 * LIMITED TO THE IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE.
 * 
 * @author AlertPay
 * @copyright 2011
 */

class TransactionHistoryAPIClient
{
    /**
     * The API's response variables
     */
    private $responseArray;

    /**
     * The server address of the Transaction History API
     */
    private $server = 'api.alertpay.com';

    /**
     * The exact URL of the Transaction History API
     */
    private $url = '/svc/api.svc/TransactionHistory';

    /**
     * Your AlertPay user name which is your email address
     */
    private $myUserName = 'seller_1_214940089@qq.com';

    /**
     * Your API password that is generated from your AlertPay account
     */
    private $apiPassword = 'wLEfVNnZZpPWPnCC';

    /**
     * The data that will be sent to the TransactionHistory API
     */
    public $dataToSend = '';


    /**
     * TransactionHistoryAPIClient::__construct()
     * 
     * Constructs a TransactionHistoryAPIClient object
     * 
     * @param string $userName Your AlertPay user name.
     * @param string $password Your API password.
     */
    public function __construct($userName, $apiPassword)
    {
        $this->myUserName = $userName;
        $this->apiPassword = $apiPassword;
        $this->dataToSend = '';
    }


    /**
     * TransactionHistoryAPIClient::setServer()
     * 
     * Sets the $server variable
     * 
     * @param string $newServer New web address of the server.
     */
    public function setServer($newServer = '')
    {
        $this->server = $newServer;
    }


    /**
     * TransactionHistoryAPIClient::getServer()
     * 
     * Returns the server variable
     * 
     * @return string A variable containing the server's web address.
     */
    public function getServer()
    {
        return $this->server;
    }


    /**
     * TransactionHistoryAPIClient::setUrl()
     * 
     * Sets the $url variable
     * 
     * @param string $newUrl New url address.
     */
    public function setUrl($newUrl = '')
    {
        $this->url = $newUrl;
    }


    /**
     * TransactionHistoryAPIClient::getUrl()
     * 
     * Returns the url variable
     * 
     * @return string A variable containing a URL address.
     */
    public function getUrl()
    {
        return $this->url;
    }

  
    /**
     * TransactionHistoryAPIClient::buildPostVariables()
     * 
     * Builds a URL encoded post string which contains the variables to be 
     * sent to the API in the correct format. 
     * 
     * @param string $startDate  The start date, formated as year/month/day, e.g., 2011/01/31.
     * @param string $endDate The end date, formated as year/month/day, e.g., 2011/03/31 (optional).
   * @param string $email The email address contained in the transaction (optional).
   * @param string $transactionReference The transaction reference number (optional).
   * @param float $amount The amount of the transaction (optional).
   * @param string $currency 3 letter ISO-4217 currency code (optional). 
   * @param int $transactionType a valid transaction type number (optional).
   * @param int $transactionState a valid transaction state (optional).
     * 
   *
   * Transaction Type Enum
   * 
   * Deposit = 2
     * Withdrawal = 3
     * Transfer Sent = 4
     * Transfer Received = 5
     * Fees = 6
     * Refund Sent = 7
     * Refund Received = 8
     * Request Sent = 9
     * Request Received = 10
     * Subscription Payment To = 11
     * Subscription Payment From = 12
     * Single Item Purchase out = 13
     * Single Item Purchase in = 14
     * Micro Payment = 15
     * Bank Transfer/Wire Withdrawal Return Fee = 16
     * Transfer Sent - No Fees = 17
     * Transfer Received - No Fees = 18
     * Currency Conversion = 19
     * Currency Conversion = 20
     * Debit = 22
     * Credit = 23
     * Chargeback Fine = 24
     * Service  Fee = 25
     * Bank Transfer Deposit Return Fee = 28
     * Credit card withdrawal return fee = 29
     * Email Invoicing Sent = 30
     * Email Invoicing Received = 31
     * Deposit by cc(for non transfer transactions) = 32
   *
   * 
   * Transaction State Enum
   *
   * Pending = 1
     * Completed = 2
     * Withdrawal - Created = 3
     * Deposit - Created = 4
     * Withdrawal - Pending Processing = 5
     * Request - Pending Acceptance = 6
     * Transfer - Pending Account Upgrade = 7
     * Transaction Cancelled = 8
     * Transaction Expired = 9
     * ACH- Withdrawal Processed = 10
     * Transaction Declined = 11
     * Deposit - Pending Processing = 12
     * ACH - Deposit Processed = 13
     * Transfer Sent = 14
     * Request Sent = 15
     * Request Sent - Email Verification = 16
     * Request Declined = 17
     * Subscription failed = 18
     * Reversed = 19
     * Bank Account Confirmation = 20
     * Bank Account Export = 21
     * Bank Transaction Returned = 22
     * Disbursement Pending for Verification = 23
     * ACH Processing = 24
     * Transaction Refunded = 25
     * Transaction Refunded affecting Balance = 26
     * Bank Transaction Reversed = 27
     * On Hold = 28
     * Pending Email Validation = 30
     * Chargeback = 31
     * Pending-Awaiting Review = 32
     * Pending CreditCard Refund = 33
     * Pending CreditCard Validation = 34
     * Completed - does not effect CC usage = 35
     * Pendig CreditCard Reversal = 36
   *  
     * @return string The URL encoded post string
     */
    public function buildPostVariables($startDate, $endDate = '', $email = '', $transactionReference = '', $amount = '', $currency = '', $transactionType = '', $transactionState = '')
    {
        $this->dataToSend = sprintf("USER=%s&PASSWORD=%s&STARTDATE=%s&ENDDATE=%s&EMAIL=%s&TRANSACTIONREFERENCE=%s&AMOUNT=%s&CURRENCY=%s&TRANSACTIONTYPE=%s&TRANSACTIONSTATE=%s",
            urlencode($this->myUserName), urlencode($this->apiPassword), urlencode((string) $startDate), 
      urlencode((string)$endDate), urlencode((string)$email), urlencode((string)$transactionReference),
      urlencode((string)$amount), urlencode((string)$currency), urlencode((string)$transactionType),
      urlencode((string)$transactionState));
        return $this->dataToSend;
    }

  
    /**
     * TransactionHistoryAPIClient::send()
     * 
     * Sends the URL encoded post string to the TransactionHistory API
     * using cURL and retrieves the response.
     * 
     * @return string The response from the TransactionHistory API.
     */
    public function send()
    {
        $response = '';

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://' . $this->getServer() . $this->getUrl());
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->dataToSend);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;
    }


    /**
     * TransactionHistoryAPIClient::parseResponse()
     * 
     * Parses the encoded response from the TransactionHistory API
     * into an associative array.
     * 
     * @param string $input The string to be parsed by the function.
     */
    public function parseResponse($input)
    {
        parse_str($input, $this->responseArray);
    }


    /**
     * TransactionHistoryAPIClient::getResponse()
     * 
     * Returns the responseArray 
     * 
     * @return string An array containing the response variables.
     */
    public function getResponse()
    {
        return $this->responseArray;
    }


    /**
     * TransactionHistoryAPIClient::__destruct()
     * 
     * Destructor of the TransactionHistoryAPIClient object
     */
    public function __destruct()
    {
        unset($this->responseArray);
    }
}
